/**
 * 系统管理  部门管理
 */
<template>
  <div>
    <!-- 搜索筛选 -->
    <el-form ref="searchFrom" :inline="true" :model="formInline" class="user-search">
      <!-- <el-form-item prop="name" label="搜索：">
        <el-input v-model="formInline.name" size="small" placeholder="输入部门名称" />
      </el-form-item>
      <el-form-item prop="code" label="">
        <el-input v-model="formInline.code" size="small" placeholder="输入部门编码" />
      </el-form-item> -->
      <el-form-item>
        <!-- <el-button size="small" type="primary" icon="el-icon-search" @click="search">
          搜索
        </el-button>
        <el-button size="small" type="primary" icon="el-icon-delete" @click="resetForm('searchFrom')">
          重置
        </el-button> -->
        <el-button size="small" type="primary" icon="el-icon-plus" @click="handleEdit()">
          添加
        </el-button>
      </el-form-item>
    </el-form>
    <!--列表-->
    <el-table
      v-loading="loading"
      element-loading-text="拼命加载中"
      :data="listData"
      style="width: 100%"
      row-key="deptId"
      border
      lazy
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column prop="name" label="部门名称" width="250" :show-overflow-tooltip="true" />
      <el-table-column prop="orderNum" label="排序" align="center" width="50" />
      <el-table-column prop="code" label="部门编码" width="200" :show-overflow-tooltip="true" />
      <el-table-column prop="createTime" label="创建时间" align="center" width="160" />
      <el-table-column prop="updateTime" label="修改时间" align="center" width="160" />
      <el-table-column align="center" label="操作" min-width="200">
        <template slot-scope="scope">
          <el-button size="mini" type="success" @click="httprequest(scope.$index, scope.row)">
            新增
          </el-button>
          <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">
            编辑
          </el-button>
          <el-button size="mini" type="danger" @click="deptDelete(scope.$index, scope.row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 编辑界面 -->
    <el-dialog
      v-if="editFormVisible"
      :title="title"
      :visible.sync="editFormVisible"
      width="30%"
      :close-on-click-modal="false"
    >
      <el-form ref="editForm" label-width="120px" :model="editForm" :rules="rules">
        <el-form-item label="上级部门" prop="parentId">
          <treeselect
            v-model="editForm.parentId"
            :options="menuOptions"
            :normalizer="normalizer"
            :show-count="true"
            placeholder="选择上级部门"
          />
        </el-form-item>
        <el-form-item label="显示排序" prop="orderNum">
          <el-input-number v-model="editForm.orderNum" controls-position="right" :min="0" />
        </el-form-item>
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="editForm.name" size="small" auto-complete="off" placeholder="请输入部门名称" />
        </el-form-item>
        <el-form-item label="部门编码" prop="code">
          <el-input v-model="editForm.code" size="small" auto-complete="off" placeholder="请输入部门编码" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeDialog">
          取消
        </el-button>
        <el-button size="small" type="primary" :loading="loading" class="title" @click="submitForm('editForm')">
          保存
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { deptList, deptSave, updateDept, deleteDept } from '@/api/userMG'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
// eslint-disable-next-line no-unused-vars
const validateNumber = (rule, value, callback) => {
  const numberReg = /^\d+$|^\d+[.]?\d+$/
  if (value !== '') {
    if (!numberReg.test(value)) {
      callback(new Error('请输入数字'))
    } else {
      // eslint-disable-next-line no-lonely-if
      if (value === '' || value === undefined || value === null) {
        callback()
      } else if (!Number(value)) {
        callback(new Error('请输入[1,20000]之间的数字'))
      } else if (value < 1 || value > 20000) {
        callback(new Error('请输入[1,20000]之间的数字'))
      } else {
        callback()
      }
    }
  } else {
    callback(new Error('请输入值'))
  }
}
export default {
  // 注册组件
  components: {
    Treeselect
  },
  data () {
    return {
      clearable: false, // 清空搜索框
      nshow: true, // switch开启
      fshow: false, // switch关闭
      loading: false, // 是显示加载
      listData: [], // 部门列表数据
      editFormVisible: false, // 控制编辑页面显示与隐藏
      disabled: false, // 是否禁用下拉框
      title: '',
      options: [], // 下拉框数据
      menuOptions: [], // 菜单树选项
      // 添加编辑
      editForm: {
        deptId: '',
        name: '',
        code: '',
        parentId: '',
        orderNum: ''
        // token: localStorage.getItem('logintoken')
      },
      // 删除部门
      seletedata: {
        deptId: ''
        // token: localStorage.getItem('logintoken')
      },
      // rules表单验证
      rules: {
        parentId: [{ required: true, message: '请选择上级部门', trigger: 'change', type: 'number' }],
        orderNum: [{ required: true, trigger: 'blur' }],
        name: [{ required: true, message: '请输入部门名称', trigger: 'blur' },
          { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }],
        code: [{ required: true, message: '请输入部门编码', trigger: 'blur' },
          { min: 3, max: 100, message: '长度在 3 到 100 个字符', trigger: 'blur' }]
      },
      formInline: {
        // pageNum: 1,
        // pageSize: 10,
        // name: '',
        // code: ''
        // token: localStorage.getItem('logintoken')
      }
    }
  },
  /**
   * 创建完毕
   */
  created () {
    this.getdata(this.formInline)
  },
  methods: {
    // 获取公司列表
    getdata (parameter) {
      this.loading = true
      /***
       * 调用接口，注释上面模拟数据 取消下面注释
       */
      deptList(parameter)
        .then((res) => {
          this.loading = false
          // eslint-disable-next-line eqeqeq
          if (res.code != 0) {
            this.$message({
              type: 'info',
              message: res.msg
            })
          } else {
            this.listData = res.data
            this.menuOptions = []
            const dept = { deptId: 0, name: '总公司', children: [] }
            dept.children = res.data
            this.menuOptions.push(dept)
          }
        })
        // eslint-disable-next-line handle-callback-err
        .catch((err) => {
          this.loading = false
          this.$message.error('菜单加载失败，请稍后再试！')
        })
    },
    // 搜索事件
    search () {
      this.formInline.pageNum = 1
      this.getdata(this.formInline)
    },
    // 重置按钮
    resetForm (formName) {
      // 重置要看 <el-form-item>的组件元素上是否指定了字段名。指定了才会重置生效
      this.$refs[formName].resetFields()
      this.formInline.pageNum = 1
      this.getdata(this.formInline)
    },
    // 显示编辑界面
    handleEdit (index, row) {
      this.editFormVisible = true
      if (row !== undefined && row !== 'undefined') {
        this.title = '编辑'
        this.disabled = true
        this.editForm.deptId = row.deptId
        this.editForm.parentId = row.parentId
        this.editForm.name = row.name
        this.editForm.code = row.code
        this.editForm.orderNum = row.orderNum
      } else {
        this.title = '添加'
        this.disabled = false
        this.editForm.deptId = ''
        this.editForm.parentId = 0
        this.editForm.name = ''
        this.editForm.code = ''
        this.editForm.orderNum = ''
      }
    },
    // 新增
    httprequest (index, row) {
      this.editFormVisible = true
      this.title = '添加'
      this.disabled = false
      this.editForm.deptId = ''
      this.editForm.parentId = row.deptId
      this.editForm.name = ''
      this.editForm.code = ''
      this.editForm.orderNum = ''
    },
    // 编辑、增加页面保存方法
    submitForm (editData) {
      this.$refs[editData].validate((valid) => {
        if (valid) {
          if (this.title === '添加') {
            deptSave(this.editForm)
              .then((res) => {
                this.editFormVisible = false
                this.loading = false
                if (res.code === 0) {
                  this.getdata(this.formInline)
                  this.$message({
                    type: 'success',
                    message: '部门保存成功！'
                  })
                } else {
                  this.$message({
                    type: 'info',
                    message: res.msg
                  })
                }
              })
              // eslint-disable-next-line handle-callback-err
              .catch((err) => {
                this.editFormVisible = false
                this.loading = false
                this.$message.error('部门保存失败，请稍后再试！')
              })
          }
          if (this.title === '编辑') {
            updateDept(this.editForm)
              .then((res) => {
                this.editFormVisible = false
                this.loading = false
                if (res.code === 0) {
                  this.getdata(this.formInline)
                  this.$message({
                    type: 'success',
                    message: '部门保存成功！'
                  })
                } else {
                  this.$message({
                    type: 'info',
                    message: res.msg
                  })
                }
              })
              // eslint-disable-next-line handle-callback-err
              .catch((err) => {
                this.editFormVisible = false
                this.loading = false
                this.$message.error('部门保存失败，请稍后再试！')
              })
          }
        } else {
          return false
        }
      })
    },
    // 删除部门
    deptDelete (index, row) {
      this.$confirm('确定要删除吗?', '信息', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          // eslint-disable-next-line no-undef
          deleteDept(row.deptId)
            .then((res) => {
              if (res.code === 0) {
                this.getdata(this.formInline)
                this.$message({
                  type: 'success',
                  message: '部门已删除!'
                })
                this.getdata(this.formInline)
              } else {
                this.$message({
                  type: 'info',
                  message: res.msg
                })
              }
            })
            // eslint-disable-next-line handle-callback-err
            .catch((err) => {
              this.loading = false
              this.$message.error('部门删除失败，请稍后再试！')
            })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 分页插件事件
    callFather (parm) {
      this.formInline.pageNum = parm.currentPage
      this.formInline.pageSize = parm.pageSize
      this.getdata(this.formInline)
    },
    // 关闭编辑、增加弹出框、并清空数据
    closeDialog () {
      this.editFormVisible = false
      // this.$refs[formName].resetFields()
      // this.$nextTick(() => {
      //   this.$refs.editForm.resetFields()
      // })
    },
    /** 转换菜单数据结构 */
    normalizer (node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.deptId,
        label: node.name,
        children: node.children
      }
    }
  }
}
</script>
<style lang="scss">

</style>
